<template>
	<scroll-view style="height: 100vh;" scroll-y :scroll-into-view="scroll" @scroll="toScroll">
    <view class="product-details pb-150">
        <!-- 头部 -->
        <view class="f ai-c jc-s-b ph-32 pv-12 hearder" :style="{ top: statusBarHeight + 'px' }" v-show="show">
            <view class="w-64 h-64 b-64 f ai-c jc-c black" @click="toBack">
                <image src="http://cwht.ricecs.cn/app/shop/back-b.png" class="w-32 h-32"></image>
            </view>
            <view class="f ai-c mp-weixin">
                <view class="w-64 h-64 b-64 f ai-c jc-c mr-20 black" @click="handleCollect">
                    <image :src="isCollect ? collectY : collectB" class="w-32 h-32"></image>
                </view>
                <view class="w-64 h-64 b-64 f ai-c jc-c black" @click="handleShare">
                    <image src="http://cwht.ricecs.cn/app/shop/share-b.png" class="w-32 h-32"></image>
                </view>
            </view>
        </view>
        <!-- 滚动头部 -->
        <view :style="{ paddingTop: statusBarHeight + 'px' }" class="roll-hearder" v-show="!show">
            <view class="h-88 ph-32 f ai-c jc-s-b">
                <view class="f ai-c">
                    <image src="../../static/back.png" class="w-40 h-33 mr-32" @click="toBack">></image>
                    <view class="fs-28 text-color3 mr-24" :class="moduleId == 'shop' ? 'active' : ''" @click="toRoll('shop')">商品</view>
                    <view class="fs-28 text-color3 mr-24" :class="moduleId == 'info' ? 'active' : ''" @click="toRoll('info')">详情</view>
                    <view class="fs-28 text-color3 mr-24" :class="moduleId == 'evaluate' ? 'active' : ''" @click="toRoll('evaluate')">评价</view>
                    <view class="fs-28 text-color3 mr-24" :class="moduleId == 'recommend' ? 'active' : ''" @click="toRoll('recommend')">推荐</view>
                </view>
                <view class="f mp-weixin">
                    <image :src="isCollect ? collectY : collectH" class="w-40 h-40 mr-32" @click="handleCollect"></image>
                    <image src="http://cwht.ricecs.cn/app/shop/share-h.png" class="w-40 h-40" @click="handleShare"></image>
                </view>
            </view>
        </view>
        <!-- 轮播图 -->
        <Banner :detail="detail" ref="banner" />
        <!-- 商品信息 -->
        <view class="teamwork ph-20 mt-22">
            <view class="b-24 content">
                <view class="box pb-24 ph-32 b-24" v-if="HeadList.length>0">
                    <view class="pt-32 pb-24 f ai-c list" v-for="(item, index) in HeadList" :key="index" :style="{ borderBottom: index == 2 - 1 ? 'none' : '' }">

                      <image :src="item.avatar" class="w-72 h-72 b-72 mr-16"></image>
                      <block v-if="item.status==1">
                        <view>
                            <view class="fs-28 fw-600 text-color4">{{item.nickname}}</view>
							<!-- 2023-10-06 12:00:00 -->
                            <view class="fs-22 text-color3">{{item.expireTime}} {{item.status==0?'拼团中':'拼团成功'}}</view>
                        </view>
                       </block>
                      <block v-if="item.status==0">
                        <view>
                          <view class="fs-28 fw-600 text-color4">还差{{item.userSize-item.userCount}}人</view>
                          <view class="fs-22 text-color3">拼单结束时间{{item.expireTime}}</view>
                        </view>
                      </block>

                    </view>

<!--										<view class="pt-32 pb-24 f ai-c list">
										          <image src="http://cwht.ricecs.cn/app/shop/query.png" class="w-72 h-72 b-72 mr-16"></image>
										          <view>
										              <view class="fs-28 fw-600 text-color4">还差一人</view>
										              <view class="fs-22 text-color3"></view>
										          </view>
										      </view>-->
                    <view class="w-f h-120 mt-8 price">
                        <image
                            :src="getBaseUrl() + '/admin-api/system/file/19/get/8117dfabc04df2b63538baf63e2b820faf04f2fcf44227581ce246b3e291d7ce.png'"
                            class="w-f h-120"
                        ></image>
                        <view class="w-f h-120 price-box ph-28 f ai-c jc-s-b">
                            <view>
                                <text class="fs-28 fw-600 mr-8 text-color5">拼团价</text>
                                <text class="fs-36 text-color5">¥</text>
                                <text class="fs-48 fw-600 text-color5">{{ detail.products[specCurt].combinationPrice }}</text>
                            </view>
                            <!-- <view class="fs-26 fw-500 text-color5">运费：¥--</view> -->
                        </view>
                    </view>
                </view>
                <view class="mt-8 ph-32 f fc-w pb-32">
                    <view
                        v-for="(item, index) in detail.products"
                        :key="index"
                        class="h-64 b-64 ph-24 f ai-c spec fs-26 text-color4 mr-16 mt-24"
                        :class="index == specCurt ? 'active' : ''"
                        @click="changeCurt(index)"
                        >{{ productsAttr[item.skuId] }}</view
                    >
                </view>
            </view>
        </view>
        <!-- 详情 -->
        <Info :detail="detail" :shopData="shopData" ref="info" id="info"/>
        <!-- 评价 -->
        	<Evaluate ref="evaluateRef" id="evaluate" :detail="detail"/>
        <!-- 推荐好货 -->
        <Recommend id="recommend" />
        <!-- 分享 -->
        <Share ref="share" />
        <!-- 底部 -->
        <view class="foot">
            <view :style="{ paddingBottom: safeAreaBottom + 'px' }" class="bot w-f">
                <view class="f ai-c jc-s-b h-100 ph-40 pv-14">
                    <view class="f ai-c jc-s-b f1 mr-30">
                        <view class="f ai-c fd-c" @click="toShop">
                            <image src="http://cwht.ricecs.cn/app/shop/shop-h.png" class="w-32 h-32"></image>
                            <view class="fs-20 text-color4 mt-8"> 店铺</view>
                        </view>
                        <view class="f ai-c fd-c" @click="handleCollect">
                            <image :src="isCollect ? collectY : collectH" class="w-32 h-32"></image>
                            <view class="fs-20 text-color4 mt-8"> 收藏</view>
                        </view>
                    </view>
                    <view class="w-506 btn h-72 b-72 f ai-c jc-c fs-28 fw-600 text-color5" disabled @click="showSpec">立即拼团 </view>
                </view>
            </view>
        </view>
        <!-- 规格 -->
        <u-popup :show="specShow" round="24rpx">
            <view class="ph-32 pt-32 specBox">
                <view class="close" @click="specShow = false"> <u-icon name="close" color="#1A1A1A" size="14"></u-icon></view>
                <view class="f jc-c">
                    <view class="w-400">
                        <u-swiper :list="detail.picUrl" height="200" radius="6" :autoplay="false" indicatorStyle="right: 20px">
                            <!-- <template v-slot:indicator>
                                <view class="current-num w-73 h-40 f ai-c jc-c">
                                    <text class="fs-24 fw-600 text-color5">{{ currentNum + 1 }}/{{ list.length }}</text>
                                </view>
                            </template> -->
                        </u-swiper>
                    </view>
                </view>
                <view class="mt-8 f fc-w pb-32">
                    <view
                        v-for="(item, index) in detail.products"
                        :key="index"
                        class="h-64 b-64 ph-24 f ai-c spec fs-26 text-color4 mr-16 mt-24"
                        :class="index == specCurt ? 'active' : ''"
                        @click="changeCurt(index)"
                        >{{ productsAttr[item.skuId] }}</view
                    >
                </view>

                <view class="ph-8 pv-20 btn">
                    <u-button text="立即拼团" color="#FABB3C" shape="circle" @click="submit"></u-button>
                </view>
            </view>
        </u-popup>
    </view>
		</scroll-view>
</template>
<script setup lang="ts">
import { ref, getCurrentInstance } from 'vue';
import { combinationActivityGetDetail, storeDetail, combinationRecordGetHeadList,spuGetDetail } from '@/services/api/shop/index';
import { addressGetDefault } from '@/services/api/address';
import { favoriteExits, favoriteCreate, favoriteDelete } from '@/services/api/shop/collect';
import { cartAdd } from '@/services/api/shop/cart';
import { onPageScroll, onReady, onLoad, onShow } from '@dcloudio/uni-app';
import collectB from '@/static/shop/collect-b.png';
import collectH from '@/static/shop/collect-h.png';
import collectY from '@/static/shop/collect-y.png';
import Banner from './Banner.vue';
import Info from './Info.vue';
import Evaluate from '../productDetails/Evaluate.vue';
import Recommend from '@/components/recommend/index.vue';
import Share from './Share.vue';
import { useAuthStore } from '@/store/modules/auth';
import { getBaseUrl } from '@/utils/env';
const authStore = useAuthStore();
const show = ref(true);
const id = ref('');
//规格
const specShow = ref(false);
const specCurt = ref(0);
const specType = ref();
const number = ref(1);
//详情
const detail = ref<any>();
const HeadList = ref<any>([]);
const productsAttr = ref<any>([]);
//是否收藏
const isCollect = ref(false);
//地址
const address = ref('');
//店铺详情
const shopData = ref('');
//滚动模块
const banner = ref();
const shop = ref();
const info = ref('');
const evaluate = ref('');
const moduleId = ref('');
const shopModule = ref(0);
const infoModule = ref(0);
const evaluateModule = ref(0);
const recommendModule = ref(0);
const { proxy } = getCurrentInstance();
const scroll=ref('')
//分享
const share = ref();
onLoad((options: any) => {
    id.value = options.id;
    getDetail();
});
onShow(() => {
    uni.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: '#ffffff',
    });
    let pages = getCurrentPages();
    let currPage: any = pages[pages.length - 1];
    let addressData = currPage.data.addressData;
    //选择地址
    if (addressData) {
        address.value = addressData;
    }
    
});
function toBack() {
    uni.navigateBack();
}
// 分享
const handleShare = () => {
    share.value.getShow(true);
};
//提交
async function submit() {
    if (specType.value === 'cart') {
        //购物车
        await cartAdd({ skuId: detail.value.id, count: number.value });
        uni.showToast({
            title: '添加成功',
        });
        specShow.value = false;
    } else {
        //立即购买
        const list = [
            {
                shop: shopData.value.name,
                goods: [
                    {
                        sku: detail.value.products[specCurt.value],
                        count: number.value,
                        spu: {
                            secondCategoryId: detail.value.secondCategoryId,
                            picUrl: detail.value.picUrl,
                            id: detail.value.id,
                            name: detail.value.name,
                        },
                    },
                ],
            },
        ];
        authStore.setOrderGoods(list);
				if(HeadList.value.length>0){
          console.log(HeadList)
					uni.navigateTo({
					    url: '/pages_shop/confirmOrder/index?combinationActivityId='+detail.value.id+'&combinationHeadId='+HeadList.value[0].headId,
					});
				}else{
					uni.navigateTo({
					    url: '/pages_shop/confirmOrder/index?combinationActivityId='+detail.value.id,
					});
				}
        
    }
}
//切换规格
const changeCurt = (data: number) => {
    specCurt.value = data;
};
//显示规格
function showSpec(type: string) {
    specShow.value = true;
    specType.value = type;
}
//跳转购物车
const toShopCart = () => {
    uni.navigateTo({
        url: '/pages_shop/shopCart/index',
    });
};
//跳转店铺
function toShop() {
    uni.navigateTo({
        url: `/pages_shop/business/index?id=${detail.value.storeId}`,
    });
}
//选择地址
function toAddress() {
    uni.navigateTo({
        url: `/pages_mine/myAddress?type=select`,
    });
}
//获取默认地址
async function getDefaultAddress() {
    const { data } = await addressGetDefault({});
    address.value = data;
}
//获取拼团列表
// 0, "进行中"
// 1, "拼团成功"
// 2, "拼团失败"
async function getCombinationRecordGetHeadList() {
    const { data } = await combinationRecordGetHeadList({ activityId: detail.value.id, status: 0 });
    data.forEach((item: any) => {
      item.expireTime = proxy.$moment(item.expireTime).format('YYYY.MM.DD HH:mm:ss');
    });
  // HeadList.value = HeadList.value.concat(data);
	HeadList.value = data
}
//详情
async function getDetail() {
    const { data } = await combinationActivityGetDetail({ id: id.value });
    data.picUrl = data.picUrl ? data.picUrl.split(',') : [];
    detail.value = data;

    getDefaultAddress();
    getFavoriteExits();
		getCombinationRecordGetHeadList();
    getShop();
    getShopDetail();
}
//检查是否收藏
async function getFavoriteExits() {
    const { data } = await favoriteExits({ id: id.value,collectionType:1 });
    isCollect.value = data;
}
//店铺详情
async function getShop() {
    const { data } = await storeDetail({ storeId: detail.value.storeId });
    shopData.value = data;
}
//商品详情
async function getShopDetail() {
    const { data } = await spuGetDetail({ id: detail.value.spuId	 });
    let products = []
    data.skus.forEach((item: any) => {
      // products.push({
      //   'spuId':item.id,
      //   'name':item.name,
      // });
      products[item.id] = item.name
    });
  detail.value.description = data.description;
  productsAttr.value = products;
}
//收藏/取消商品
async function handleCollect() {
    isCollect.value = !isCollect.value;
    if (isCollect.value) {
        await favoriteCreate({ id: id.value,collectionType:1 });
    } else {
        await favoriteDelete({ id: id.value,collectionType:1 });
    }
}
//头部底部
const systemInfo = uni.getSystemInfoSync();
const statusBarHeight = systemInfo.statusBarHeight;
let safeArea = systemInfo.safeArea;
let screenHeight = systemInfo.screenHeight;
let safeAreaBottom = screenHeight - safeArea.bottom;
//滚动
onReady(() => {
    uni.createSelectorQuery()
        .select('#shop')
        .boundingClientRect((rect: any) => {
            shopModule.value = rect.top;
            console.log('商品：', rect);
        })
        .exec();
    uni.createSelectorQuery()
        .select('#info')
        .boundingClientRect((rect: any) => {
            infoModule.value = rect.top;
            console.log('详情：', rect);
        })
        .exec();
    uni.createSelectorQuery()
        .select('#evaluate')
        .boundingClientRect((rect: any) => {
            evaluateModule.value = rect.top;
            console.log('评价：', rect);
        })
        .exec();
    uni.createSelectorQuery()
        .select('#recommend')
        .boundingClientRect((rect: any) => {
            recommendModule.value = rect.top;
            console.log('推荐：', rect);
        })
        .exec();
});
onPageScroll((e) => {
    if (e.scrollTop < 100) {
        show.value = true;
    } else {
        show.value = false;
    }
    if (e.scrollTop > 100 && e.scrollTop < shopModule.value) {
        moduleId.value = 'shop';
    } else if (e.scrollTop > shopModule.value && e.scrollTop < infoModule.value) {
        moduleId.value = 'info';
    } else if (e.scrollTop > infoModule.value && e.scrollTop < evaluateModule.value) {
        moduleId.value = 'evaluate';
    } else if (e.scrollTop > evaluateModule.value && e.scrollTop < recommendModule.value) {
        moduleId.value = 'recommend';
    }
});
function toScroll(e){
		if (e.scrollTop < 100) {
			show.value = true;
		} else {
			show.value = false;
		}
		
	}
	const toRoll = (type:string) => {
		scroll.value=type
		moduleId.value=type
		// if (type == 'shop') {
		// 	uni.pageScrollTo({
		// 		scrollTop: shopModule.value - 100,
		// 		duration: 200,
		// 	});
		// } else if (type == 'info') {
		// 	uni.pageScrollTo({
		// 		scrollTop: infoModule.value - 100,
		// 		duration: 200,
		// 	});
		// } else if (type == 'evaluate') {
		// 	uni.pageScrollTo({
		// 		scrollTop: evaluateModule.value - 100,
		// 		duration: 200,
		// 	});
		// } else if (type == 'recommend') {
		// 	uni.pageScrollTo({
		// 		scrollTop: recommendModule.value - 100,
		// 		duration: 200,
		// 	});
		// }
	};
</script>
<style lang="scss" scoped>
.specBox {
    background: #fff;
    position: relative;
    border-radius: 24rpx 24rpx 0 0;
    .spec {
        background: #f5f5f5;
    }
    .active {
        background: #faf5e6;
        color: #fabb3c;
    }
    .current-num {
        background: rgba(0, 0, 0, 0.4);
        border-radius: 20rpx;
    }
    .btn {
        border-top: 1px solid #f5f5f5;
    }
    ::v-deep .u-button__text {
        font-size: 36rpx !important;
        font-weight: 600 !important;
    }
    ::v-deep .u-button {
        height: 96rpx !important;
    }

    .close {
        position: absolute;
        right: 34rpx;
        top: 34rpx;
    }
}
::v-deep button {
    padding: 0;
    margin: 0;
    background-color: #fff;
    line-height: 0;
    width: 40rpx;
    height: 80rpx;
}
.foot {
    .btn {
        background: #fabb3c;
    }

    .bot {
        position: fixed;
        left: 0;
        bottom: 0;
        background: #fff;
        .add-cart {
            border: 2rpx solid #fabb3c;
        }
        .buy {
            background: #fabb3c;
        }
        ::v-deep .u-button__text {
            font-size: 28rpx !important;
            font-weight: 600 !important;
            color: #fff;
        }
        ::v-deep .u-button {
            height: 72rpx !important;
            padding: 0 !important;
        }
    }
}
.teamwork {
    .content {
        background: #fff;
        .spec {
            background: #f5f5f5;
        }
        .active {
            background: #faf5e6;
            color: #fabb3c;
        }
    }
    .box {
        background-image: linear-gradient(180deg, #ffffff 0%, #faf0dc 100%);
        .price {
            position: relative;
            .price-box {
                position: absolute;
                left: 0;
                top: 0;
            }
        }
        .list {
            border-bottom: 1px solid #f0f0f0;
        }
    }
}
.product-details {
    background: #f5f5f5;
    min-height: 100vh;
    //#ifdef MP-WEIXIN
    .mp-weixin {
        margin-right: 170rpx;
    }
    //#endif
    .roll-hearder {
        background: #fff;
        position: fixed;
        width: 100%;
        left: 0;
        top: 0;
        z-index: 111;
        .active {
            font-weight: 600;
            color: #fac519;
        }
    }
    .to-top {
        border: 1rpx solid #dddddd;
        box-shadow: 0 2rpx 12rpx 0 #0000000f;
        position: fixed;
        right: 20rpx;
        bottom: 200rpx;
        background: #fff;
    }
    // .bot {
    //     position: fixed;
    //     left: 0;
    //     bottom: 0;
    //     background: #fff;
    //     .add-cart {
    //         border: 2rpx solid #fabb3c;
    //     }
    //     .buy {
    //         background: #fabb3c;
    //     }
    //     ::v-deep .u-button__text {
    //         font-size: 28rpx !important;
    //         font-weight: 600 !important;
    //         color: #fff;
    //     }
    //     ::v-deep .u-button {
    //         height: 72rpx !important;
    //         padding: 0 !important;
    //     }
    // }
    .hearder {
        position: fixed;
        width: 100%;
        left: 0;
        top: 0;
        z-index: 111;
    }
    .black {
        background: rgba(0, 0, 0, 0.4);
    }
}
</style>
